import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ocr_plugin_example/life_state.dart';
// import 'package:path_provider/path_provider.dart';
// import 'package:permission_handler/permission_handler.dart';

import 'package:ocr_plugin/id_card_info.dart';

import 'ocr_rect_page.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorObservers: [lifeObserver],
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() =>_HomePageState();
}

class _HomePageState extends State<HomePage>{

  IdCardInfo _idCardInfo = IdCardInfo();
  String? _tips;

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Scaffold(
        appBar: AppBar(
          title: const Text('id card ocr recognition'),
        ),
        body: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              if(_tips != null)_info("提示", _tips),
              _imgWidget(file: _idCardInfo.portraitUrl),
              _imgWidget(file: _idCardInfo.backUrl, portrait: false),
              _info("姓名", _idCardInfo.name),
              _info("身份证号码", _idCardInfo.num),
              _info("性别", _idCardInfo.sex),
              _info("民族", _idCardInfo.folk),
              _info("出生日期", _idCardInfo.birt),
              _info("户籍地址", _idCardInfo.addr),
              _info("机构", _idCardInfo.issue),
              _info("有效期", _idCardInfo.valid),
              _info("头像地址", _idCardInfo.headPath),
              _info("文件地址", _idCardInfo.imgPath),
              _info("头像照地址", _idCardInfo.portraitUrl),
              _info("国徽照地址", _idCardInfo.backUrl),
            ],
          ),
        ),
      ),
    );
  }


  Widget _imgWidget({bool portrait = true, String? file}) {
    return Container(
      margin: EdgeInsets.fromLTRB(15, 10, 15, 5),
      width: double.infinity,
      height: 151, //宽高比 240/151
      decoration: BoxDecoration(
        border: Border.all(color: Color(0xff404040)),
      ),
      child: InkWell(
        onTap: () {
          _imgPress(portrait);
        },
        child: file == null
            ? Center(child: Text(portrait ? "头像照" : "国徽照"))
            : Image(image: FileImageEx(File(file)),fit: BoxFit.contain)
            // : Image.file(new File(file), fit: BoxFit.contain),
      ),
    );
  }

  Widget _info(String title, String? content) {
    return Row(
      children: [
        Container(child: Text(title), padding: EdgeInsets.all(15)),
        Expanded(child: Text(content ?? '', softWrap: true)),
      ],
    );
  }

  void _imgPress(bool portrait) async{
    // Map<Permission, PermissionStatus> per = await [Permission.camera, Permission.storage].request();
    // bool can = true;
    // String tips = '';
    // per.forEach((key, value) {
    //   can = can && value.isGranted;
    //   if(!value.isGranted){ tips = "${tips}permission $key is $value,";}
    //   print("ocr permission key $key , value $value");
    // });
    // if(!can){
    //   setState(() {
    //     _tips = tips;
    //   });
    //   print("ocr recognition no camera permission");
    //   return;
    // }
    // _tips = null;
    // var parent = Platform.isIOS ? await getTemporaryDirectory() : await getExternalStorageDirectory();
    // //跳转识别页面
    // String? path =  "${parent?.path}/${portrait?'portrait':'back'}.jpg";
    // String? second =  "${parent?.path}/${portrait?'portrait2':'back2'}.jpg";
    // print("path $path \n second $second");

    /// 1.相机权限，在原生相机功能才做判断
    /// 2.图片保存路径为可选像，原生保存功能对路径判空，可不传
    /// 3.拍照功能，需要原生把图片转正


    var result = await Navigator.push(context, MaterialPageRoute(builder: (cont) {
      return OcrRectPage();
      // return OcrRectPage(filePath: parent == null ? null : path,secondPath: second);
    }));
    //处理返回结果
    print("OcrRectPage back result $result");
    if(result is Map){
      IdCardInfo info = IdCardInfo.fromJson(result);
      //华为的云端图片,没有真正存在手机中
      if(info.imgPath != null && !File(info.imgPath!).existsSync()){
        _tips = "image path file no exist,path ${info.imgPath}";
        info.imgPath = null;
      }
      _idCardInfo.update(portrait, info);
      setState(() {
      });
    }
  }
}

///文件路径不改，内容改了，防止还是显示旧内容
class FileImageEx extends FileImage{

  final int fileSize;

  FileImageEx(File file, {double scale = 1.0})
      : fileSize = file.lengthSync(),
        super(file, scale: scale);

  @override
  bool operator == (Object other) {
    if(other.runtimeType != runtimeType) return false;
    if(other is FileImageEx){
      final FileImageEx oth = other;
      return file.path == oth.file.path && scale == oth.scale && fileSize == oth.fileSize;
    }
    return false;
  }

  @override
  int get hashCode => super.hashCode;

}
